package org.zhxy.zhxy.controller.backend;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.zhxy.zhxy.dao.AppointRecordDao;
import org.zhxy.zhxy.dao.UserDao;
import org.zhxy.zhxy.entity.AppointRecord;
import org.zhxy.zhxy.entity.Notice;
import org.zhxy.zhxy.entity.User;
import org.zhxy.zhxy.service.AppointRecordService;
import org.zhxy.zhxy.utils.EmailUtils;
import org.zhxy.zhxy.utils.PageResult;
import org.zhxy.zhxy.utils.Result;
import org.zhxy.zhxy.utils.SendEmailUtils;

import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 项目名称: zhxy
 * 作者: zhaojs
 * 创建日期: 2024年10月20日
 * 文件说明: 见类描述
 */
@RestController
@RequestMapping("/api/admin")
public class AdminAppointRecordController {

    @Resource
    private AppointRecordService appointRecordService;

    @Resource
    private AppointRecordDao appointRecordDao;

    @Resource
    private UserDao userDao;

    @Resource
    private SendEmailUtils SendEmailUtils;

    /**
     * 预约申请审核
     */
    @PostMapping("/appoint/audit")
    public Result auditAppoint(@RequestBody Map<String, Object> params) {
        Integer id = (Integer) params.get("id");
        Integer status = (Integer) params.get("status");
        if (id == null || status == null) {
            return Result.fail("参数错误");
        }

        if (status == 2) {
            //不通过
            User user = userDao.selectById(appointRecordDao.selectById(id).getUserId());
            SendEmailUtils.sendEmail(user.getEmail(), "预约申请未通过", "您的预约申请未通过，请重新预约！");
            return appointRecordService.updateStatusById(id, status) ? Result.success("更新成功") : Result.fail("更新失败");
        } else if (status == 1) {
            //通过
            AppointRecord appointRecord = appointRecordDao.selectById(id);
            // 格式化 applyDate
            Date applyDate = appointRecord.getApplyDate();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = dateFormat.format(applyDate);
            //先查记录看下是否这个时间段已经有人通过预约
            AppointRecord appointRecord2 = appointRecordService.query()
                    .eq("status", 1)
                    .eq("apply_date", formattedDate)
                    .and(wrapper -> {
                        wrapper.ge("start_time", appointRecord.getStartTime()).le("start_time", appointRecord.getEndTime())
                                .or()
                                .ge("end_time", appointRecord.getStartTime()).le("end_time", appointRecord.getEndTime())
                                .or()
                                .lt("start_time", appointRecord.getStartTime()).gt("end_time", appointRecord.getEndTime());
                    })
                    .last("LIMIT 1")
                    .one();
            //没有通过则插入记录，通过则返回操作失败
            if (appointRecord2 == null) {
                User user = userDao.selectById(appointRecord.getUserId());
                SendEmailUtils.sendEmail(user.getEmail(), "预约申请已通过", "您的预约申请已通过！");
                appointRecordService.updateStatusById(id, status);
                return Result.success("更新成功");
            } else {
                return Result.fail("该时间段已有预约通过");
            }
        } else {
            return Result.fail("操作错误");
        }
    }

    /**
     * 预约申请审核列表
     */
    @GetMapping("/appoint/list")
    public Result listAppoint(@NotNull(message = "页码不能为空") int page, @NotNull(message = "页码不能为空") int pageSize) {
        //        Page<AppointRecord> appointRecordPage = appointRecordService.query()
        //                .eq("status", 0)
        //                .page(new Page<>(page, pageSize));
        Page<AppointRecord> appointRecordPage = appointRecordService.listAppoint(page, pageSize);
        PageResult<AppointRecord> pageResult = new PageResult<>(appointRecordPage.getTotal(), appointRecordPage.getRecords());
        return Result.success(pageResult);
    }

    /**
     * 预约申请审核查询
     */
    @GetMapping("/appoint/query")
    public Result queryAppoint(String studentId, String applyDate, Long startTime, Long endTime, @NotNull(message = "页码不能为空") int page, @NotNull(message = "页码不能为空") int pageSize) {
        Page<AppointRecord> appointRecordPage = appointRecordService.queryAppoint(studentId, applyDate, startTime, endTime, page, pageSize);
        PageResult<AppointRecord> pageResult = new PageResult<>(appointRecordPage.getTotal(), appointRecordPage.getRecords());
        return Result.success(pageResult);
    }

    /**
     * 预约记录列表
     */
    @GetMapping("/appoint/record/list")
    public Result listAppointRecord(@NotNull(message = "页码不能为空") int page, @NotNull(message = "页码不能为空") int pageSize) {
        //        Page<AppointRecord> appointRecordPage = appointRecordService.query()
        //                .in("status", 1, 2)
        //                .page(new Page<>(page, pageSize));
        //        PageResult<AppointRecord> pageResult = new PageResult<>(appointRecordPage.getTotal(), appointRecordPage.getRecords());
        Page<AppointRecord> appointRecordPage = appointRecordService.queryAppointRecord(null, page, pageSize);
        PageResult<AppointRecord> pageResult = new PageResult<>(appointRecordPage.getTotal(), appointRecordPage.getRecords());
        return Result.success(pageResult);
    }

    /**
     * 删除预约记录
     */
    @DeleteMapping("/appoint/record/delete")
    public Result deleteAppointRecord(@NotNull(message = "id不能为空") Integer id) {
        return appointRecordService.removeById(id) ? Result.success("删除成功") : Result.fail("删除失败");
    }

    /**
     * 批量删除预约记录
     */
    @DeleteMapping("/appoint/record/deleteBatch")
    public Result deleteBatchAppointRecord(@NotEmpty(message = "id列表不能为空") @RequestBody List<Integer> ids) {
        return appointRecordService.removeBatchByIds(ids) ? Result.success("删除成功") : Result.fail("删除失败");
    }

    /**
     * 预约记录查询
     */
    @GetMapping("/appoint/record/query")
    public Result queryAppointRecord(String studentId, @NotNull(message = "页码不能为空") int page, @NotNull(message = "页码不能为空") int pageSize) {
        Page<AppointRecord> appointRecordPage = appointRecordService.queryAppointRecord(studentId, page, pageSize);
        PageResult<AppointRecord> pageResult = new PageResult<>(appointRecordPage.getTotal(), appointRecordPage.getRecords());
        return Result.success(pageResult);
    }
}
